package com.agile.leetcode.rpc.service.impl;

import com.agile.leetcode.rpc.service.Calculator;
import com.agile.leetcode.rpc.pojo.CalculatorRpcRequest;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * @Author KD
 * @Date 2021/1/19 15:08
 */
public class CalculatorImpl implements Calculator {
    @Override
    public Integer add(int a, int b) {
        Socket socket = null;
        // 对象输出流
        ObjectOutputStream objectOutputStream = null;
        ObjectInputStream objectInputStream = null;
        try {
            // 创建socket
            socket = new Socket("127.0.0.1", 7001);
            // 创建传输对象
            CalculatorRpcRequest calculatorRpcRequest = new CalculatorRpcRequest(a, b, "add");
            // 初始化对象输出流
            objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            // 将传输参数输出
            objectOutputStream.writeObject(calculatorRpcRequest);
            // 拿到服务器写回的输入流
            InputStream inputStream = socket.getInputStream();
            // 包装
            objectInputStream = new ObjectInputStream(inputStream);
            // 读取对象
            Object object = objectInputStream.readObject();
            if (object instanceof Integer) {
                return (Integer) object;
            } else {
                throw new RuntimeException("未知错误");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (objectInputStream != null) {
                    objectInputStream.close();
                }
                if (objectOutputStream != null) {
                    objectOutputStream.close();
                }
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }

        }
        return null;
    }
}
